//
//  TBUncaughtExceptionHandler.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/3/31.
//

import UIKit

class TBUncaughtExceptionHandler: NSObject {
    
    static let shared = TBUncaughtExceptionHandler()
    
    fileprivate override init() {
    }
    
    public func exceptionLogWithData() {
        setDefaultHandler()
        let path = getdataPath()
//        print(path)
        let data = NSData.init(contentsOfFile: path)
        if data != nil {
            //            let crushStr = String.init(data: data! as Data, encoding: String.Encoding.utf8)
            //            print(crushStr!)
            //上传数据
//            sendExceptionLogWithData(data: data! as Data, path: path)
            
        }
        
        //测试数据
//        let arry:NSArray = ["1"]
//        print("%@",arry[5])
        
    }
    
    ///沙盒路径
    fileprivate func getdataPath() -> String{
        let str = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!
        let urlPath = str.appending("/Exception.txt")
        return urlPath
    }
    
    ///异常回调
    fileprivate func setDefaultHandler() {
        NSSetUncaughtExceptionHandler { (exception) in
            let arr:NSArray = exception.callStackSymbols as NSArray
            let reason:String = exception.reason!
            let name:String = exception.name.rawValue
            let date:NSDate = NSDate()
            let timeFormatter = DateFormatter()
            timeFormatter.dateFormat = "YYYY/MM/dd hh:mm:ss SS"
            let strNowTime = timeFormatter.string(from: date as Date) as String
            let url:String = String.init(format: "========异常错误报告========\ntime:%@\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@",strNowTime,name,reason,arr.componentsJoined(by: "\n"))
            let documentpath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!
            let path = documentpath.appending("/Exception.txt")
            do{
                try
                    url.write(toFile: path, atomically: true, encoding: String.Encoding.utf8)
            }catch{}
        }
    }
    
    ///上传
//    fileprivate func sendExceptionLogWithData(data:Data,path:String){
//        let manager = AFHTTPSessionManager()
//        manager.requestSerializer.timeoutInterval = 5.0
//        AFJSONResponseSerializer().acceptableContentTypes = NSSet(object: "text/plain") as? Set<String>
//        manager.post("服务器地址", parameters: nil, constructingBodyWith: { (formData) in
//            formData.appendPart(withFileData: data, name: "file", fileName: "Exception.txt", mimeType: "txt")
//        }, progress: nil, success: { (task, responseObject) in
//            let fileManger = FileManager.default
//            do {
//                try fileManger.removeItem(atPath: path)
//            }catch{
//
//            }
//        }) { (task, error) in
//            //上传失败
//            print(error)
//        }
//    }
}
